package com.xoa.service.diary.impl;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;


import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.xoa.dao.common.SysCodeMapper;
import com.xoa.dao.common.SysParaMapper;
import com.xoa.dao.department.DepartmentMapper;
import com.xoa.dao.diary.DiaryCommentModelMapper;
import com.xoa.dao.diary.DiaryCommentReplyModelMapper;
import com.xoa.dao.diary.DiaryTopMapper;
import com.xoa.dao.users.UserPrivMapper;
import com.xoa.dao.users.UsersMapper;
import com.xoa.dev.qywx.service.QywxService;
import com.xoa.model.common.SysCode;
import com.xoa.model.common.SysPara;
import com.xoa.model.crm.FollowExample;
import com.xoa.model.diary.DiaryCommentModel;
import com.xoa.model.diary.DiaryCommentReplyModel;
import com.xoa.model.diary.DiaryTop;
import com.xoa.model.sms.SmsBody;
import com.xoa.model.users.UserPriv;
import com.xoa.model.users.Users;
import com.xoa.service.sms.SmsService;
import com.xoa.service.users.UsersService;
import com.xoa.util.*;
import com.xoa.util.common.StringUtils;
import com.xoa.util.common.log.FileUtils;
import com.xoa.util.common.session.SessionUtils;
import com.xoa.util.dataSource.ContextHolder;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import com.xoa.dao.diary.DiaryModelMapper;
import com.xoa.model.department.Department;
import com.xoa.model.diary.DiaryModel;
import com.xoa.model.enclosure.Attachment;
import com.xoa.model.file.FileSortModel;
import com.xoa.service.department.DepartmentService;
import com.xoa.service.diary.DiaryService;
import com.xoa.util.common.L;
import com.xoa.util.common.constants.RegExpConstants;
import com.xoa.util.page.PageParams;
import org.springframework.transaction.annotation.Transactional;

/**
 * 创建作者:   杨 胜
 * 创建日期:   2017-4-19 上午9:23:32
 * 类介绍  :    工作日志
 * 构造参数:
 */
@Service
public class DiaryServiceImpl implements DiaryService {
    private Logger loger = Logger.getLogger(DiaryServiceImpl.class);

    @Resource
    DiaryModelMapper diaryModelMapper;

    @Resource
    DiaryCommentModelMapper diaryCommentModelMapper;

    @Resource
    UsersService usersService;

    @Resource
    DiaryCommentReplyModelMapper diaryCommentReplyModelMapper;

    @Resource
    DiaryTopMapper diaryTopMapper;

    @Resource
    DepartmentService departmentService;

    @Resource
    UsersMapper usersMapper;

    @Resource
    SysParaMapper sysParaMapper;

    @Resource
    ThreadPoolTaskExecutor threadPoolTaskExecutor;

    @Resource
    SysCodeMapper sysCodeMapper;

    @Resource
    SmsService smsService;

    @Resource
    QywxService qywxService;

    @Resource
    DepartmentMapper departmentMapper;

    @Resource
    UserPrivMapper userPrivMapper;

    /**
     * @Author 廉立深
     * @Description 优化工作日志查询
     * @Date 11:05 2020/5/20
     * @Param [request, diaryModel]
     * @return com.xoa.util.ToJson<com.xoa.model.diary.DiaryModel>
     **/
    @Override
    public ToJson<DiaryModel> findDiaryGet(HttpServletRequest request,
                                           DiaryModel diaryModel,
                                           String type,
                                           Integer page,
                                           Integer limit) {
        ToJson toJson = new ToJson(0, "暂无数据");
        try {
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
            Users user = usersMapper.getUserId(users.getUserId());
            Map<String, Object> diaryMap = new HashMap();

            //选择的日期，普通的日期查询
            diaryMap.put("diaDate",diaryModel.getDiaDate());

            if (!StringUtils.checkNull(type) && type.equals("1")){
                //我的日志
                diaryMap.put("userIds", new String[]{user.getUserId()});

                //高级查询,有结束时间一定是高级查询
                if (!StringUtils.checkNull(diaryModel.getTimeEnd())){
                    diaryMap.clear();
                    diaryMap.put("timeBegin",diaryModel.getDiaDate());
                    diaryMap.put("timeEnd",diaryModel.getTimeEnd());
                    String diaryUserId = user.getUserId();

                    //因为是我的日志所以在选择部门和角色也查不出数据
                    /*if (!StringUtils.checkNull(diaryModel.getDeptIds()) || !StringUtils.checkNull(diaryModel.getUserPrivs()) || !StringUtils.checkNull(diaryModel.getUserIds())){
                        if (!StringUtils.checkNull(diaryModel.getDeptIds()) && ",".equals(String.valueOf(diaryModel.getDeptIds().charAt(diaryModel.getDeptIds().length()-1)))){
                            diaryModel.setDeptIds(diaryModel.getDeptIds().substring(0,diaryModel.getDeptIds().length()-1));
                        }
                        if (!StringUtils.checkNull(diaryModel.getUserPrivs()) && ",".equals(String.valueOf(diaryModel.getUserPrivs().charAt(diaryModel.getUserPrivs().length()-1)))){
                            diaryModel.setUserPrivs(diaryModel.getUserPrivs().substring(0,diaryModel.getUserPrivs().length()-1));
                        }
                        Map map=new HashMap();
                        map.put("viewDepts",diaryModel.getDeptIds());
                        map.put("viewPrivs",diaryModel.getUserPrivs());
                        map.put("viewUsers",!StringUtils.checkNull(diaryModel.getUserIds()) ? diaryModel.getUserIds().split(",") : null);
                        //根据部门，角色和userId查询用户UserId
                        diaryUserId = diaryModelMapper.findDiaryUserId(map);
                    }*/

                    diaryMap.put("userIds", diaryUserId.split(","));
                }
            }else if (!StringUtils.checkNull(type) && type.equals("2")){
                //共享日志
                diaryMap.put("userIdOther", user.getUserId());
                diaryMap.put("diaType", "1");

                //高级查询,有结束时间一定是高级查询
                if (!StringUtils.checkNull(diaryModel.getTimeEnd())){
                    diaryMap.clear();

                    diaryMap.put("timeBegin",diaryModel.getDiaDate());
                    diaryMap.put("timeEnd",diaryModel.getTimeEnd());

                    String diaryUserId = user.getUserId();
                    if (!StringUtils.checkNull(diaryModel.getDeptIds()) || !StringUtils.checkNull(diaryModel.getUserPrivs()) || !StringUtils.checkNull(diaryModel.getUserIds())) {

                        if (!StringUtils.checkNull(diaryModel.getDeptIds()) && ",".equals(String.valueOf(diaryModel.getDeptIds().charAt(diaryModel.getDeptIds().length()-1)))){
                            diaryModel.setDeptIds(diaryModel.getDeptIds().substring(0,diaryModel.getDeptIds().length()-1));
                        }

                        if (!StringUtils.checkNull(diaryModel.getUserPrivs()) && ",".equals(String.valueOf(diaryModel.getUserPrivs().charAt(diaryModel.getUserPrivs().length()-1)))){
                            diaryModel.setUserPrivs(diaryModel.getUserPrivs().substring(0,diaryModel.getUserPrivs().length()-1));
                        }

                        //根据部门，角色和userId查询用户UserId
                        Map map = new HashMap();
                        map.put("viewDepts", diaryModel.getDeptIds().split(","));
                        map.put("viewPrivs", diaryModel.getUserPrivs().split(","));
                        map.put("viewUsers", !StringUtils.checkNull(diaryModel.getUserIds()) ? diaryModel.getUserIds().split(",") : null);
                        diaryUserId = diaryModelMapper.findDiaryUserId(map);
                    }
                    diaryMap.put("userIds", diaryUserId.split(","));
                }
            }else if (!StringUtils.checkNull(type) && type.equals("3")){
                //下属日志

                //查询下面的角色,得到下属角色
                String UserPrivs = diaryModelMapper.findDauserPrivs(user.getUserPriv().toString());

                //查询下级部门，得到下属部门
                StringBuffer stringBuffer = new StringBuffer();
                StringBuffer getDeptIds = findChildDept(stringBuffer, user.getDeptId().toString());
                String getDeptId=getDeptIds.toString();

                if (",".equals(String.valueOf(getDeptId.charAt(getDeptId.length()-1)))){
                    getDeptId=getDeptId.substring(0,getDeptId.length()-1);
                }

                //根据部门，角色和userId查询用户UserId，得到下属用户
                Map map=new HashMap();
                map.put("viewDepts",getDeptId.split(","));
                map.put("viewPrivs",UserPrivs.split(","));
                map.put("viewUsers",new String[]{user.getUserId()});
                String diaryUserId = diaryModelMapper.findDiaryUserId(map);


                //高级查询
                if (!StringUtils.checkNull(diaryModel.getTimeEnd())) {
                    diaryMap.clear();

                    //下属日志高级查询
                    diaryMap.put("timeBegin",diaryModel.getDiaDate());
                    diaryMap.put("timeEnd",diaryModel.getTimeEnd());


                    //判断角色是否在下属里,角色只需要比较大大小就好
                    if (!StringUtils.checkNull(diaryModel.getUserPrivs())){
                        String userPrivs="";
                        //传入的角色
                        String[] split = diaryModel.getUserPrivs().split(",");
                        for (String priv:split) {
                            if (!StringUtils.checkNull(priv) && Integer.parseInt(priv)>=user.getUserPriv()){
                                userPrivs+=priv+",";
                            }
                        }

                        //截取，号
                        if (",".equals(String.valueOf(userPrivs.charAt(userPrivs.length()-1)))){
                            UserPrivs=userPrivs.substring(0,userPrivs.length()-1);
                        }
                    }else{
                        UserPrivs="";
                    }

                    //判断部门是否在下级部门里，部门不像角色一样，这个进行判断是否包含
                    if (!StringUtils.checkNull(diaryModel.getDeptIds()) && !StringUtils.checkNull(getDeptId)){
                        String getdeptid="";
                        //下属部门
                        String[] split1 = getDeptId.split(",");
                        List<String> strings = Arrays.asList(split1);

                        //获取要查询的部门
                        String[] split = diaryModel.getDeptIds().split(",");
                        for (String dept:split) {
                            //不等与空 并且  包含在下属里
                            if (!StringUtils.checkNull(dept) && strings.contains(dept)){
                                getdeptid+=dept+",";
                            }
                        }

                        //截取，号
                        if (!StringUtils.checkNull(getdeptid) && ",".equals(String.valueOf(getdeptid.charAt(getdeptid.length()-1)))){
                            getDeptId=getdeptid.substring(0,getdeptid.length()-1);
                        }
                    }else{
                        getDeptId="";
                    }


                    //在判断用户是否在下属里面
                    if (!StringUtils.checkNull(diaryModel.getUserIds())){
                        String userids="";
                        //下属的用户
                        String[] split = diaryUserId.split(",");
                        List<String> strings = Arrays.asList(split);

                        String[] split1 = diaryModel.getUserIds().split(",");
                        for (String userid:split1) {
                            if (!StringUtils.checkNull(userid) && strings.contains(userid)){
                                userids+=userid+",";
                            }
                        }

                        if (!StringUtils.checkNull(userids) && ",".equals(String.valueOf(userids.charAt(userids.length()-1)))){
                            diaryUserId=userids.substring(0,userids.length()-1);
                        }
                    }else{
                        diaryUserId="";
                    }

                    //部门 角色  用户  都判断完成之后再次进行查询用户
                    Map map2=new HashMap();
                    map2.put("viewDepts",getDeptId.split(","));
                    map2.put("viewPrivs",UserPrivs.split(","));
                    map2.put("viewUsers",!StringUtils.checkNull(diaryUserId) ? diaryUserId.split(",") : null);
                    diaryUserId=diaryModelMapper.findDiaryUserId(map2);
                }
                diaryMap.put("userIds", diaryUserId.split(","));
            }

            List<DiaryModel> diarySelf2 = diaryModelMapper.findDiarySelf(diaryMap);

            diaryMap.put("page",(page-1)*limit);
            diaryMap.put("pageSize",limit);
            List<DiaryModel> diarySelf = diaryModelMapper.findDiarySelf(diaryMap);

            SysPara is_comments = sysParaMapper.querySysPara("IS_COMMENTS");
            for (DiaryModel dm : diarySelf) {
                //当前登录人
                Users user2 = usersMapper.getUserId(dm.getUserId());
                dm.setUserName(user2.getUserName());
                dm.setPhoto(user2.getPhoto());
                dm.setAvatar(user2.getAvatar());
                dm.setSex(user2.getSex());
                dm.setUid(user2.getUid());

                String tempDiaTime = dm.getDiaTime();
                if(dm.getDiaTime().length()>19){
                    tempDiaTime = dm.getDiaTime().substring(0, 19);
                }

                String tempReaders = this.readerFlag(diaryModel.getUserId(), dm.getReaders());
                if (diaryModel.getPostType() != null && "1".equals(diaryModel.getPostType())) {
                    String tempContent = dm.getContent().replaceAll(RegExpConstants.verifyHtml, "").replaceAll(RegExpConstants.verifyHtml2, "").
                            replaceAll(RegExpConstants.verifyFormat, "");
                    if (tempContent.length() > 60) {
                        tempContent.substring(0, 59);
                    }
                    dm.setContent(tempContent);
                }
                dm.setReaders(tempReaders);
                dm.setDiaTime(tempDiaTime);

                // 查询评论数
                dm.setComTotal(diaryCommentModelMapper.getDiaryCommentCount(dm.getDiaId()));
                if (!dm.getUserId().equals(diaryModel.getUserId())) {
                    dm.setIsComments(Integer.valueOf(is_comments.getParaValue()));
                }

                // 查询用户信息
                Users usersByuserId = usersMapper.SimplefindUsersByuserId(dm.getUserId());
                if(usersByuserId!=null){
                    dm.setUserPrivName(usersByuserId.getUserPrivName());
                    dm.setDeptName(usersByuserId.getDeptName());
                }

                // 查询分享人姓名
                String userNames = usersService.getUserNameById(dm.getToId());
                if(!StringUtils.checkNull(userNames)){
                    //加个逗号用于前端拼接人
                    dm.setToIdName(userNames+",");
                }

                // 查询是否被置顶
                DiaryTop diaryTopByDiaId = diaryTopMapper.getDiaryTopByDiaId(String.valueOf(dm.getDiaId()));
                if (diaryTopByDiaId == null) {
                    dm.setTopFlag("0");
                } else {
                    dm.setTopFlag("1");
                }

                //附件处理
                if(dm.getAttachmentName()!=null&&!"".equals(dm.getAttachmentName())){
                    List<Attachment> attachmentList= GetAttachmentListUtil.returnAttachment(dm.getAttachmentName(),dm.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"),GetAttachmentListUtil.MODULE_DIARY);
                    dm.setAttachment(attachmentList);
                }
            }

            //查看别人的数量
            Department deptById = departmentMapper.getDeptById(user.getDeptId());
            List<Department> list1 = departmentMapper.getChDeptByDeptNo(deptById.getDeptId(),deptById.getDeptNo());

            int size  = list1.size();
            String [] arr = new String[size+1];
            int x=0;
            for (Department department:list1){
                arr[x]=department.getDeptId()+"";
                x++;
            }
            arr[size]=users.getDeptId()+"";
            List<Users> userPrivsByDeptID = usersMapper.getUserPrivsByDeptID(arr);
            StringBuffer stringBuffer=new StringBuffer();
            int n=0;
            for (Users users1: userPrivsByDeptID){
                if (users1.getUserPriv()>=users.getUserPriv()){
                    if (n==0){
                        stringBuffer.append(users1.getUserId());
                    }else if (n > 0){
                        stringBuffer.append(","+users1.getUserId());
                    }
                    n++;
                }
            }
            sortDiaryList(diarySelf);
            toJson.setObj(diarySelf);
            toJson.setTotleNum(diarySelf2.size());
            toJson.setMsg("ok");
            toJson.setFlag(0);
        }catch (Exception e){
            e.printStackTrace();
            toJson.setMsg(e.getMessage());
        }
        return toJson;
    }

    private StringBuffer findChildDept(StringBuffer stringBuffer,String deptId){
        List<String> childDept = diaryModelMapper.findChildDept(deptId);
        for (String dept:childDept) {
            stringBuffer.append(dept).append(",");
            List<String> childDept2 = diaryModelMapper.findChildDept(dept);
            if (!childDept2.isEmpty()){
                findChildDept(stringBuffer,dept);
            }
        }
        return stringBuffer;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-4-19 下午4:41:51
     * 方法介绍:   工作日志首页接口
     * 参数说明:   @param diaryModel
     * 参数说明:   @return
     *
     * @return ToJson<DiaryModel> 取得的首页加载内容
     */
    public ToJson<DiaryModel> getDiaryIndex(DiaryModel diaryModel, PageParams pageParams,HttpServletRequest request) {
        Map<String, Object> diaryMap = new HashMap<String, Object>();
        //用户Id
        diaryMap.put("userId", diaryModel.getUserId());
        diaryMap.put("pageParams", pageParams);
        diaryMap.put("searchValue",diaryModel.getSearchValue());
        //我的日志
        List<DiaryModel> diaryList = diaryModelMapper.getDiarySelf(diaryMap);


        //修改
        for(DiaryModel diaryModel3:diaryList){
            DiaryModel diary = diaryModelMapper.getDiaryById(diaryModel3.getDiaId()+"");
            if (!StringUtils.checkNull(diary.getDiaId()+"")) {
                diaryModel3.setDiaId(diary.getDiaId());
            }
            if (!StringUtils.checkNull(diary.getSubject()+"")) {
                diaryModel3.setSubject(diary.getSubject());
            }
            if (!StringUtils.checkNull(diary.getUserId())) {
                diaryModel3.setUserId(diary.getUserId());
            }
            if (!StringUtils.checkNull(diary.getDiaTime())) {
                diaryModel3.setDiaTime(diary.getDiaTime());
            }
            if (!StringUtils.checkNull(diary.getDiaType())) {
                diaryModel3.setDiaType(diary.getDiaType());
            }
            if (!StringUtils.checkNull(diary.getLastCommentTime())) {
                diaryModel3.setLastCommentTime(diary.getLastCommentTime());
            }
            if (!StringUtils.checkNull(diary.getToAll()+"")) {
                diaryModel3.setToAll(diary.getToAll());
            }
            if (!StringUtils.checkNull(diary.getCrmDiary()+"")) {
                diaryModel3.setCrmDiary(diary.getCrmDiary());
            }
            if (!StringUtils.checkNull(diary.getContent())) {
                diaryModel3.setContent(diary.getContent());
            }
            if (!StringUtils.checkNull(diary.getAttachmentId())) {
                diaryModel3.setAttachmentId(diary.getAttachmentId());
            }
            if (!StringUtils.checkNull(diary.getAttachmentName())) {
                diaryModel3.setAttachmentName(diary.getAttachmentName());
            }
            if (!StringUtils.checkNull(diary.getToId())) {
                diaryModel3.setToId(diary.getToId());
            }
            if (!StringUtils.checkNull(diary.getReaders())) {
                diaryModel3.setReaders(diary.getReaders());
            }
            Users user = usersMapper.getUserByDiaryId(diaryModel3.getUserId());
            diaryModel3.setUserName(user.getUserName());
            diaryModel3.setPhoto(user.getPhoto());
            diaryModel3.setAvatar(user.getAvatar());
            diaryModel3.setSex(user.getSex());
            diaryModel3.setUid(user.getUid());
        }
        Map<String, Object> diaryMapCount = new HashMap<String, Object>();
        diaryMapCount.put("userId", diaryModel.getUserId());
        //       int countSelf = diaryModelMapper.getCountSelf(diaryMapCount);
        for (DiaryModel dm : diaryList) {
            String tempDiaTime = dm.getDiaTime();
            if(dm.getDiaTime().length()>19){
                tempDiaTime = dm.getDiaTime().substring(0, 19);
            }
            String tempReaders = this.readerFlag(diaryModel.getUserId(), dm.getReaders());//\\s*|\t|\r|\n   .substring(0, 59)
            if (diaryModel.getPostType() != null && "1".equals(diaryModel.getPostType())) {
                String tempContent = dm.getContent().replaceAll(RegExpConstants.verifyHtml, "").replaceAll(RegExpConstants.verifyHtml2, "").
                        replaceAll(RegExpConstants.verifyFormat, "");
                if (tempContent.length() > 60) {
                    tempContent.substring(0, 59);
                }
                dm.setContent(tempContent);
            }
            dm.setReaders(tempReaders);
            dm.setDiaTime(tempDiaTime);
            // 查询评论数
            dm.setComTotal(diaryCommentModelMapper.getDiaryCommentCount(dm.getDiaId()));
            // 查询用户信息
            Users usersByuserId = usersMapper.SimplefindUsersByuserId(dm.getUserId());
            if(usersByuserId!=null){
                dm.setUserPrivName(usersByuserId.getUserPrivName());
                dm.setDeptName(usersByuserId.getDeptName());
            }
            // 查询分享人姓名
            String userNames = usersService.getUserNameById(dm.getToId());
            if(!StringUtils.checkNull(userNames)){
                //加个逗号用于前端拼接人
                dm.setToIdName(userNames+",");
            }
            // 查询是否被置顶
            DiaryTop diaryTopByDiaId = diaryTopMapper.getDiaryTopByDiaId(String.valueOf(dm.getDiaId()));
            if (diaryTopByDiaId == null) {
                dm.setTopFlag("0");
            } else {
                dm.setTopFlag("1");
            }
            //附件处理
            List<Attachment> attachmentList=new ArrayList<Attachment>();
            if(dm.getAttachmentName()!=null&&!"".equals(dm.getAttachmentName())){
                attachmentList= GetAttachmentListUtil.returnAttachment(dm.getAttachmentName(),dm.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"),GetAttachmentListUtil.MODULE_DIARY);
            }
            dm.setAttachment(attachmentList);
        }
       /* // 排序
        sortDiaryList(diaryList);*/
        //取得别人日志日志数量
        Map<String, Object> otherdiaryMap = new HashMap<String, Object>();
        otherdiaryMap.put("userIdOther", diaryModel.getUserId());
        otherdiaryMap.put("diaTypeOther", "2");
        otherdiaryMap.put("searchValue",diaryModel.getSearchValue());
        //查看别人的数量
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        Integer count=0;
        //判断是否是管理员
     /*   if(users.getUserPriv().intValue()==1){
            count = diaryModelMapper.getAdminCountDiartOther(otherdiaryMap);
        }
        else{
            count = diaryModelMapper.getCountDiaryOther(otherdiaryMap);
        }*/
        List<DiaryModel> diaryAllList =new ArrayList<DiaryModel>();
        //判断是否是管理员
    /*    if(users.getUserPriv().intValue()==1){
            diaryAllList = diaryModelMapper.getAdminDiaryList(diaryMap);
        }
        else{
            diaryAllList = diaryModelMapper.getDiaryList(diaryMap);
        }*/
        Department deptById = departmentMapper.getDeptById(users.getDeptId());
        List<Department> list1 = departmentMapper.getChDeptByDeptNo(deptById.getDeptId(),deptById.getDeptNo());

        int size  = list1.size();
        String [] arr = new String[size+1];
        int x=0;
        for (Department department:list1){
            arr[x]=department.getDeptId()+"";
            x++;
        }
        arr[size]=users.getDeptId()+"";
        List<Users> userPrivsByDeptID = usersMapper.getUserPrivsByDeptID(arr);
        StringBuffer stringBuffer=new StringBuffer();
        int n=0;
        for (Users users1: userPrivsByDeptID){
            if (users1.getUserPriv()>=users.getUserPriv()){
                if (n==0){
                    stringBuffer.append(users1.getUserId());
                }else if (n > 0){
                    stringBuffer.append(","+users1.getUserId());
                }
                n++;
            }
        }
        String s=new String(stringBuffer);
        String [] split=s.split(",");
//        Integer count2=diaryModelMapper.getCountDiarySubord(split);



//		   Iterator<DiaryModel> iteratorcountList=countList.iterator();
//			while(iteratorcountList.hasNext()){
//				DiaryModel dm=iteratorcountList.next();
//				if("0".equals(dm.getToAll())){
//					 String[] dmStrings=dm.getToId().split(",");
//					 List<String> userList = Arrays.asList(dmStrings);
//					if(!userList.contains(diaryModel.getUserId())){
//						iteratorcountList.remove();
//						}
//				}
//			}

        ToJson<DiaryModel> diaryListToJson = new ToJson<DiaryModel>(0, (200 + "," + 200 + "," + 0));
        diaryListToJson.setObj(diaryList);
        diaryListToJson.setTotleNum(pageParams.getTotal());
        return diaryListToJson;
    }


    /**
     * 创建作者:   高亚峰
     * 创建日期:   2017-4-19 下午4:41:51
     * 方法介绍:   工作日志首页接口
     * 参数说明:   @param diaryModel
     * 参数说明:   @return
     *
     * @return ToJson<DiaryModel> 取得的首页加载内容
     */
    public ToJson<DiaryModel> PregetIndex(DiaryModel diaryModel, PageParams pageParams,HttpServletRequest request) {
        Map<String, Object> diaryMap = new HashMap<String, Object>();
        //用户Id
        diaryMap.put("userId", diaryModel.getUserId());
        diaryMap.put("pageParams", pageParams);
        diaryMap.put("diaType",diaryModel.getDiaType());
        //我的日志
        List<DiaryModel> diaryList = diaryModelMapper.getDiarySelf(diaryMap);

        Map<String, Object> diaryMapCount = new HashMap<String, Object>();
        diaryMapCount.put("userId", diaryModel.getUserId());
        int countSelf = diaryModelMapper.getCountSelf(diaryMapCount);
        for (DiaryModel dm : diaryList) {
            String tempDiaTime = dm.getDiaTime();
            if(dm.getDiaTime().length()>19){
                tempDiaTime = dm.getDiaTime().substring(0, 19);
            }
            String tempReaders = this.readerFlag(diaryModel.getUserId(), dm.getReaders());//\\s*|\t|\r|\n   .substring(0, 59)
            if (diaryModel.getPostType() != null && "1".equals(diaryModel.getPostType())) {
                String tempContent = dm.getContent().replaceAll(RegExpConstants.verifyHtml, "").replaceAll(RegExpConstants.verifyHtml2, "").
                        replaceAll(RegExpConstants.verifyFormat, "");
                if (tempContent.length() > 60) {
                    tempContent.substring(0, 59);
                }
                dm.setContent(tempContent);
            }
            dm.setReaders(tempReaders);
            dm.setDiaTime(tempDiaTime);
            // 查询评论数
            dm.setComTotal(diaryCommentModelMapper.getDiaryCommentCount(dm.getDiaId()));
            // 查询用户信息
            Users usersByuserId = usersMapper.SimplefindUsersByuserId(dm.getUserId());
            if(usersByuserId!=null){
                dm.setUserPrivName(usersByuserId.getUserPrivName());
                dm.setDeptName(usersByuserId.getDeptName());
            }
            // 查询是否被置顶
            DiaryTop diaryTopByDiaId = diaryTopMapper.getDiaryTopByDiaId(String.valueOf(dm.getDiaId()));
            if (diaryTopByDiaId == null) {
                dm.setTopFlag("0");
            } else {
                dm.setTopFlag("1");
            }
            //附件处理
            List<Attachment> attachmentList=new ArrayList<Attachment>();
            if(dm.getAttachmentName()!=null&&!"".equals(dm.getAttachmentName())){
                attachmentList= GetAttachmentListUtil.returnAttachment(dm.getAttachmentName(),dm.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"),GetAttachmentListUtil.MODULE_DIARY);
            }
            dm.setAttachment(attachmentList);
        }
        ToJson<DiaryModel> diaryListToJson = new ToJson<DiaryModel>();
        diaryListToJson.setObj(diaryList);
        diaryListToJson.setTotleNum(pageParams.getTotal());
        return diaryListToJson;
    }



    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-4-19 下午6:58:23
     * 方法介绍:   取得全部共享日志
     * 参数说明:   @param diaryModel
     * 参数说明:   @return
     *
     * @return ToJson<DiaryModel>
     */
    public ToJson<DiaryModel> getDiaryAll(DiaryModel diaryModel, PageParams pageParams,HttpServletRequest request) {
        Map<String, Object> diaryMap = new HashMap<String, Object>();
        diaryMap.put("userId", diaryModel.getUserId());
        diaryMap.put("diaType", "2");
        diaryMap.put("page", pageParams);
        diaryMap.put("searchValue",diaryModel.getSearchValue());
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        List<DiaryModel> diaryAllList =new ArrayList<DiaryModel>();
        Department deptById = departmentMapper.getDeptById(users.getDeptId());
        List<Department> list1 = departmentMapper.getChDeptByDeptNo(deptById.getDeptId(),deptById.getDeptNo());

        int size  = list1.size();
        String [] arr = new String[size+1];
        int x=0;
        for (Department department:list1){
            arr[x]=department.getDeptId()+"";
            x++;
        }
        arr[size]=users.getDeptId()+"";
        List<Users> userPrivsByDeptID = usersMapper.getUserPrivsByDeptID(arr);
        StringBuffer stringBuffer=new StringBuffer();
        int n=0;
        UserPriv userPriv = userPrivMapper.selectByPrimaryKey(users.getUserPriv());
        for (Users users1: userPrivsByDeptID){
            if (users1.getUserPrivNo()>userPriv.getPrivNo()){
                if (n==0){
                    stringBuffer.append(users1.getUserId());
                }else if (n > 0){
                    stringBuffer.append(","+users1.getUserId());
                }
                n++;
            }
        }
        String s=new String(stringBuffer);
        String [] split=s.split(",");
        diaryMap.put("page", pageParams.getPage()-1);
        diaryMap.put("pageSize", pageParams.getPageSize());
        List<String> list=new ArrayList<>();
        for (String s1:split){
            if(!users.getUserId().equals(s1)){
                list.add(s1);
            }
        }
        diaryMap.put("list",list);
        diaryMap.put("userId",users.getUserId());
        diaryAllList = diaryModelMapper.getDiaryListByIds(diaryMap);
        pageParams.setTotal(diaryModelMapper.getDiaryListByIdsCount(diaryMap));

        for(DiaryModel diaryModel3:diaryAllList){
            DiaryModel diary = diaryModelMapper.getDiaryById(diaryModel3.getDiaId()+"");
            if (!StringUtils.checkNull(diary.getDiaId()+"")) {
                diaryModel3.setDiaId(diary.getDiaId());
            }
            if (!StringUtils.checkNull(diary.getSubject()+"")) {
                diaryModel3.setSubject(diary.getSubject());
            }
            if (!StringUtils.checkNull(diary.getUserId())) {
                diaryModel3.setUserId(diary.getUserId());
            }
            if (!StringUtils.checkNull(diary.getDiaTime())) {
                diaryModel3.setDiaTime(diary.getDiaTime());
            }
            if (!StringUtils.checkNull(diary.getDiaType())) {
                diaryModel3.setDiaType(diary.getDiaType());
            }
            if (!StringUtils.checkNull(diary.getLastCommentTime())) {
                diaryModel3.setLastCommentTime(diary.getLastCommentTime());
            }
            if (!StringUtils.checkNull(diary.getToAll()+"")) {
                diaryModel3.setToAll(diary.getToAll());
            }
            if (!StringUtils.checkNull(diary.getCrmDiary()+"")) {
                diaryModel3.setCrmDiary(diary.getCrmDiary());
            }
            if (!StringUtils.checkNull(diary.getContent())) {
                diaryModel3.setContent(diary.getContent());
            }
            if (!StringUtils.checkNull(diary.getAttachmentId())) {
                diaryModel3.setAttachmentId(diary.getAttachmentId());
            }
            if (!StringUtils.checkNull(diary.getAttachmentName())) {
                diaryModel3.setAttachmentName(diary.getAttachmentName());
            }
            if (!StringUtils.checkNull(diary.getToId())) {
                diaryModel3.setToId(diary.getToId());
            }
            if (!StringUtils.checkNull(diary.getReaders())) {
                diaryModel3.setReaders(diary.getReaders());
            }
            Users user = usersMapper.getUserByDiaryId(diaryModel3.getUserId());
            diaryModel3.setUserName(user.getUserName());
            diaryModel3.setPhoto(user.getPhoto());
            diaryModel3.setAvatar(user.getAvatar());
            diaryModel3.setSex(user.getSex());
            diaryModel3.setUid(user.getUid());
        }
        for (DiaryModel diaryModel1:diaryAllList){
            if (!StringUtils.checkNull(diaryModel.getUserId())){
                diaryModel.setUserName(usersMapper.getUsernameByUserId(diaryModel.getUserId()));
            }
        }
        Iterator<DiaryModel> iterator = diaryAllList.iterator();
        SysPara is_comments = sysParaMapper.querySysPara("IS_COMMENTS");
        while (iterator.hasNext()) {
            DiaryModel dm = iterator.next();
            //附件处理
            List<Attachment> attachmentList=new ArrayList<Attachment>();
            if(dm.getAttachmentName()!=null&&!"".equals(dm.getAttachmentName())){
                attachmentList= GetAttachmentListUtil.returnAttachment(dm.getAttachmentName(),dm.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"),GetAttachmentListUtil.MODULE_DIARY);
            }
            dm.setAttachment(attachmentList);
            if(!StringUtils.checkNull(dm.getDiaTime())){
                String temp = dm.getDiaTime().substring(0, 19);
                dm.setDiaTime(temp);
            }
            // 查询评论数
            dm.setComTotal(diaryCommentModelMapper.getDiaryCommentCount(dm.getDiaId()));
            if (!dm.getUserId().equals(diaryModel.getUserId())) {
                dm.setIsComments(Integer.valueOf(is_comments.getParaValue()));
            }
            // 查询用户信息
            Users usersByuserId = usersMapper.findUsersByuserId(dm.getUserId());
            if(usersByuserId!=null){
                dm.setUserPrivName(usersByuserId.getUserPrivName());
                dm.setDeptName(usersByuserId.getDeptName());
            }
            // 查询分享人姓名
            String userNames = usersService.getUserNameById(dm.getToId());
            if(!StringUtils.checkNull(userNames)){
                //加个逗号用于前端拼接人
                dm.setToIdName(userNames+",");
            }
            // 查询是否被置顶
            DiaryTop diaryTopByDiaId = diaryTopMapper.getDiaryTopByDiaId(String.valueOf(dm.getDiaId()));
            if (diaryTopByDiaId == null) {
                dm.setTopFlag("0");
            } else {
                dm.setTopFlag("1");
            }

            dm.setReaders(this.readerFlag(diaryModel.getUserId(), dm.getReaders()));

//				if(dm.getUserId()!=diaryModel.getUserId()||!dm.getUserId().equals(diaryModel.getUserId())){
//				if(!"1".equals(dm.getToAll())){
//					 String[] dmStrings=dm.getToId().split(",");
//					 List<String> userList = Arrays.asList(dmStrings);
//					if(!userList.contains(diaryModel.getUserId())){
//						iterator.remove();
//					  }
//				 }
//				}
        }
        // 排序
        // sortDiaryList(diaryAllList);
        ToJson<DiaryModel> diaryListToJson = new ToJson<DiaryModel>(0, "");
        diaryListToJson.setObj(diaryAllList);
        diaryListToJson.setTotleNum(pageParams.getTotal());
        return diaryListToJson;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-4-19 下午6:58:23
     * 方法介绍:   取得他人共享日志
     * 参数说明:   @param diaryModel
     * 参数说明:   @return
     *
     * @return ToJson<DiaryModel>
     */
    public ToJson<DiaryModel> getDiaryOther(DiaryModel diaryModel, PageParams pageParams,HttpServletRequest request) {
        Map<String, Object> diaryMap = new HashMap<String, Object>();
        diaryMap.put("userIdOther", diaryModel.getUserId());
        diaryMap.put("diaTypeOther", "2");
        diaryMap.put("searchValue",diaryModel.getSearchValue());
        diaryMap.put("page",(pageParams.getPage()-1)*pageParams.getPageSize());
        diaryMap.put("pageSize",pageParams.getPageSize());
        //他人日志
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        List<DiaryModel> otherdiaryList=new ArrayList<DiaryModel>();
        //判断是否是管理员
        if(users.getUserPriv()==1){
            otherdiaryList = diaryModelMapper.getAdminDiaryOtherList(diaryMap);
            pageParams.setTotal(diaryModelMapper.getAdminDiaryOtherListCount(diaryMap));
        }else{
            otherdiaryList = diaryModelMapper.getDiaryOtherList(diaryMap);
            pageParams.setTotal(diaryModelMapper.getDiaryOtherListCount(diaryMap));
        }
        // 查询是否允许评论
        SysPara is_comments = sysParaMapper.querySysPara("IS_COMMENTS");
        //加入权限处理字段
        for (DiaryModel dm : otherdiaryList) {

            String tempReaders = this.readerFlag(diaryModel.getUserId(), dm.getReaders());//\\s*|\t|\r|\n
            if (diaryModel.getPostType() != null && "1".equals(diaryModel.getPostType())) {
                String tempContent = dm.getContent().replaceAll(RegExpConstants.verifyHtml, "").replaceAll(RegExpConstants.verifyHtml2, "").
                        replaceAll(RegExpConstants.verifyFormat, "");
                if (tempContent.length() > 60) {
                    tempContent.substring(0, 59);
                }
                dm.setContent(tempContent);
            }
            //附件处理
            List<Attachment> attachmentList=new ArrayList<Attachment>();
            if(dm.getAttachmentName()!=null&&!"".equals(dm.getAttachmentName())){
                attachmentList= GetAttachmentListUtil.returnAttachment(dm.getAttachmentName(),dm.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"),GetAttachmentListUtil.MODULE_DIARY);
            }
            dm.setAttachment(attachmentList);
            dm.setReaders(tempReaders);
            if(!StringUtils.checkNull(dm.getDiaTime())){
                String tempDiaTime = dm.getDiaTime().substring(0, 19);
                dm.setDiaTime(tempDiaTime);
            }
            // 查询评论数
            dm.setComTotal(diaryCommentModelMapper.getDiaryCommentCount(dm.getDiaId()));
            // 查询用户信息
            Users usersByuserId = usersMapper.SimplefindUsersByuserId(dm.getUserId());
            if(usersByuserId!=null){
                dm.setUserPrivName(usersByuserId.getUserPrivName());
                dm.setDeptName(usersByuserId.getDeptName());
            }
            // 查询分享人姓名
            String userNames = usersService.getUserNameById(dm.getToId());
            if(!StringUtils.checkNull(userNames)){
                //加个逗号用于前端拼接人
                dm.setToIdName(userNames+",");
            }

            // 添加是否允许评论
            dm.setIsComments(Integer.valueOf(is_comments.getParaValue()));
            // 查询是否被置顶
            DiaryTop diaryTopByDiaId = diaryTopMapper.getDiaryTopByDiaId(String.valueOf(dm.getDiaId()));
            if (diaryTopByDiaId == null) {
                dm.setTopFlag("0");
            } else {
                dm.setTopFlag("1");
            }

        }
        // 排序
        sortDiaryList(otherdiaryList);
        ToJson<DiaryModel> diaryListToJson = new ToJson<DiaryModel>(0, "");
        diaryListToJson.setObj(otherdiaryList);
        diaryListToJson.setTotleNum(pageParams.getTotal());
        return diaryListToJson;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-4-19 下午3:10:17
     * 方法介绍:   工作日志添加操作
     * 参数说明:   @param diaryModel
     * 参数说明:   @return
     *
     * @return int 添加数量影响行
     * @throws DataFormatException
     */
    public int saveDiary(DiaryModel diaryModel,HttpServletRequest request){
        int count= diaryModelMapper.saveDiary(diaryModel);
        if(count >0 && !StringUtils.checkNull(diaryModel.getToId())){
            //当SendRemind==1时发送提醒
            if(diaryModel.getSendRemind()==1){
                addAffairs(diaryModel,request);
            }
        }
        return count;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-4-19 下午3:39:29
     * 方法介绍:   工作日志编辑操作
     * 参数说明:   @param diaryModel
     * 参数说明:   @return
     *
     * @return int  修改
     */
    public int updateDiary(DiaryModel diaryModel,HttpServletRequest request) {
        //更新最近一次修改时间
        diaryModel.setDiaTime(DateFormat.getStrDate(new Date()));
        String toId="";
        int count= diaryModelMapper.updateDiary(diaryModel);
        if(count >0 && !StringUtils.checkNull(diaryModel.getToId())){
            if(diaryModel.getSendRemind()==1){
                toId=diaryModel.getToId();
                DiaryModel model=diaryModelMapper.getDiaryByDiaId(diaryModel);
                model.setEditFlag("1");
                model.setToId(toId);
                addAffairs(model,request);
            }
        }
        return count;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-4-19 下午3:39:29
     * 方法介绍:   工作日志根据ID删除
     * 参数说明:   @param diaryModel
     * 参数说明:   @return
     *
     * @return int  修改
     */
    @Override
    public int deletDiaById(DiaryModel diaryModel) {
        int count = 0;
        count = diaryModelMapper.deletDiaById(diaryModel);
        List<DiaryCommentModel> diaryCommentModelList = diaryCommentModelMapper.getDiaryCommentByDiaId(diaryModel.getDiaId().toString());
        if (count != 0) {
            for (DiaryCommentModel diaryCommentModel : diaryCommentModelList) {
                diaryCommentModelMapper.delDiaryCommentByCommentId(diaryCommentModel.getCommentId().toString());
                diaryCommentReplyModelMapper.delCommentReplyByCommentId(diaryCommentModel.getCommentId().toString());
            }
        }
        return count;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-4-19 下午3:39:29
     * 方法介绍:   通过DiaId取得日志详情 并设置已读未读
     * 参数说明:   @param diaryModel
     * 参数说明:   @return
     *
     * @return ToJson<DiaryModel> 详情单条列表对象
     */
    public ToJson<Attachment> getDiaryByDiaId(DiaryModel diaryModel, String sqlType) {
        ToJson<Attachment> diaryListToJson = new ToJson<Attachment>(0, "");
        DiaryModel diary = diaryModelMapper.getDiaryByDiaId(diaryModel);
        if (diary == null) {
            return diaryListToJson;
        }
        if ("0".equals(readerFlag(diaryModel.getUserId(), diary.getReaders()))) {
            diary.setReaders(diary.getReaders() + diaryModel.getUserId() + ",");
            diaryModelMapper.updateReadersByDiaId(diary);
        }
        if(!StringUtils.checkNull(diary.getDiaTime())){
            String temp = diary.getDiaTime().substring(0, 19);
            diary.setDiaTime(temp);
        }
        if (diary.getToId() != null && !"".equals(diary.getToId())) {
            String[] toIds = diary.getToId().split(",");
            String[] toIds2 = null;
            if(toIds.length>10){
                toIds2 = new String[10];
                System.arraycopy(toIds,0,toIds2,0,10);
                toIds=toIds2;
            }
            List<Users> userByUserIds = usersMapper.getUserByUserIds(toIds);
            StringBuilder names = new StringBuilder("");
            StringBuilder ids = new StringBuilder("");
            for (Users u : userByUserIds) {
                ids.append(u.getUserId());
                ids.append(",");
                names.append(u.getUserName());
                names.append(",");
            }
            diary.setToId(ids.toString());
            diary.setToIdName(names.toString());
            if(diary.getDeptId() != null){
                diary.setDeptName(departmentService.getDeptById(diary.getDeptId()).getDeptName());
            }
        } else {
            diary.setToIdName("");
        }
        diary.setReaders("");
        List<Attachment> attachmentList = new ArrayList<Attachment>();
        if (diary.getAttachmentName() != null && !"".equals(diary.getAttachmentName())) {
            attachmentList = GetAttachmentListUtil.returnAttachment(diary.getAttachmentName(), diary.getAttachmentId(), sqlType, GetAttachmentListUtil.MODULE_DIARY);
        }
        // 查询评论数
        diary.setComTotal(diaryCommentModelMapper.getDiaryCommentCount(diaryModel.getDiaId()));
        diary.setAttachment(attachmentList);
        diaryListToJson.setObject(diary);
        return diaryListToJson;
    }
    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-6-12 上午11:16:00
     * 方法介绍:   工作日志模块高级查询请求调用方法
     * 参数说明:   @param mapSelectParameter
     * 参数说明:   @return
     *
     * @return ToJson<DiaryModel>
     */
    public ToJson<DiaryModel> diarySelect(Map<String, String> mapSelectParameter, HttpServletRequest request) {
        ToJson<DiaryModel> toJson = new ToJson<DiaryModel>();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users  users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        String userid = users.getUserId();
        //查询时间 开始
        String startBegin = mapSelectParameter.get("startBegin");
        String time = getString(mapSelectParameter.get("time"));
        //查询时间 结束
        String startEnd = mapSelectParameter.get("startEnd");
        //查询范围 用户范围
        String userIdStrings = getString(mapSelectParameter.get("userId"));
        //查询范围 角色范围
        String userPrivStrings = getString(mapSelectParameter.get("userPriv"));
        //查询范围 用户范围
        String deptIdStrings = getString(mapSelectParameter.get("deptIds"));
        //传值map
        Map<String, Object> diaryMap = new HashMap<String, Object>();
        //分页
        PageParams pageParams = new PageParams();
        pageParams.setPage(Integer.parseInt(mapSelectParameter.get("page")));
        pageParams.setPageSize(Integer.parseInt(mapSelectParameter.get("pageSize")));
        pageParams.setUseFlag(Boolean.valueOf(mapSelectParameter.get("useFlag")));
        diaryMap.put("page", pageParams);

        diaryMap.put("userId", userid);
        diaryMap.put("diaType", "1");
        diaryMap.put("time", time);
        diaryMap.put("adminType",users.getUserPriv());
        // 拼写时间
        if (startBegin != null&&!"".equals(startBegin)) {
            diaryMap.put("timeBegin", startBegin+" 00:00:00");
        }
        if (startEnd != null&&!"".equals(startEnd)) {
            diaryMap.put("timeEnd", startEnd+" 23:59:59");
        }
        //时间日期
        List<String> userIdList = new ArrayList<String>();

        Department deptById = departmentMapper.getDeptById(users.getDeptId());
        List<Department> list1 = departmentMapper.getChDeptByDeptNo(deptById.getDeptId(),deptById.getDeptNo());
        int size  = list1.size();
        String [] arr ;
        if (!"".equals(deptIdStrings)) {
            String[] deptId = deptIdStrings.split(",");
            StringBuffer stringBuffer=new StringBuffer();
            for (String s:deptId){
                Department deptById2 = departmentMapper.getDeptById(Integer.parseInt(s));
                List<Department> list2 = departmentMapper.getChDeptByDeptNo(deptById2.getDeptId(),deptById2.getDeptNo());
                int n=0;
                for (Department department:list2){
                    for (Department department2:list1){
                        if (department.getDeptId().equals(department2.getDeptId())){
                            if (n==0){
                                stringBuffer.append(department2.getDeptId());
                                n++;
                            }else if (n > 0){
                                stringBuffer.append(","+department2.getDeptId());
                            }
                        }
                    }
                }
            }
            arr=stringBuffer.toString().split(",");
            if(StringUtils.checkNull(stringBuffer.toString())){
                toJson.setObject("您未查到该部门用户的信息");
                toJson.setFlag(0);
                return toJson;
            }
        }else {
            arr= new String[size+1];
            int x=0;
            for (Department department:list1){
                arr[x]=department.getDeptId()+"";
                x++;
            }
            arr[size]=users.getDeptId()+"";
        }
        List<Users> userPrivsByDeptID = usersMapper.getUserPrivsByDeptID(arr);

        StringBuffer stringBuffer=new StringBuffer();
        List<String> list=new ArrayList<>();
        if (!"".equals(userPrivStrings)) {
            String[] userPrivs = userPrivStrings.split(",");
            int n=0;
            for(String s:userPrivs){
                UserPriv userPriv = userPrivMapper.selectByPrimaryKey(Integer.parseInt(s));
                for (Users users1: userPrivsByDeptID){
                    if (users1.getUserPrivNo()>userPriv.getPrivNo()){
                        if (n==0){
                            stringBuffer.append(users1.getUserId());
                        }else if (n > 0){
                            stringBuffer.append(","+users1.getUserId());
                        }
                        n++;
                    }
                }
            }
        }else {
            int n=0;
            for (Users users1: userPrivsByDeptID){
                UserPriv userPriv = userPrivMapper.selectByPrimaryKey(users.getUserPriv());
                if (users1.getUserPrivNo()>userPriv.getPrivNo()){
                    if (n==0){
                        stringBuffer.append(users1.getUserId());
                    }else if (n > 0){
                        stringBuffer.append(","+users1.getUserId());
                    }
                    n++;
                }
            }
        }
        String s=new String(stringBuffer);
        String [] split=s.split(",");

        if (!"".equals(userIdStrings)) {
            String[] userIds = userIdStrings.split(",");
            for (String s1:userIds){
                for (String s2:split){
                    if (s1.equals(s2)){
                        list.add(s1);
                    }
                }
            }
            userIdList.addAll(list);
        }else {
            for (String s2:split){
                list.add(s2);
            }
            userIdList=list;
        }
        diaryMap.put("userIds", userIdList);
        if(userIdList.size()==0){
            toJson.setObject("您没有权限查询该用户");
            toJson.setFlag(0);
            return toJson;
        }
        //查询范围  1、所有人   2、我自己的  3、 共享给我的  4、 有权限查看的 5.根据日期查询
        String queryScope = getString(mapSelectParameter.get("queryScope"));
        List<DiaryModel> diaryList = new ArrayList<DiaryModel>();
        List<String> diaryModels2=new ArrayList<>() ;
        Integer u=0;
        switch (Integer.parseInt(queryScope)) {
            case 1:
                diaryList = diaryModelMapper.diarySelectOne(diaryMap);
                diaryModels2 = diaryModelMapper.diarySelectOneUser(diaryMap);
                u= diaryModelMapper.getDiaryListByIdsCount2(diaryMap);
                break;
            case 2:
                diaryList = diaryModelMapper.diarySelectTwo(diaryMap);
                u= diaryModelMapper.diarySelectTwoCounts(diaryMap);
                break;
            case 3:
                diaryList = diaryModelMapper.diarySelectThree(diaryMap);
                break;
            case 4:
                diaryList = diaryModelMapper.diarySelectOne(diaryMap);
                u= diaryModelMapper.getDiaryListByIdsCount2(diaryMap);
                diaryModels2 = diaryModelMapper.diarySelectOneUser(diaryMap);
                break;
            case 5:
                diaryList = diaryModelMapper.diarySelectFive(diaryMap);
                break;
            default:
                toJson.setMsg("没有该查询条件设置");
                break;
        }
        Set<String> diaryModels=new HashSet<>();
        if(diaryModels2.size()!=0){
            for (String s7:diaryModels2){
                diaryModels.add(s7);
            }
        }
        List<String> users2List=new ArrayList<>();
        for (String s1:userIdList){
            int i=0;
            for (String diaryModel1:diaryModels){
                if (!s1.equals(diaryModel1)){
                    i++;
                }
                if (i==diaryModels.size()){
                    users2List.add(s1);
                }
            }
        }
        if (users2List.size()==0){
            toJson.setObject("暂无人员未发送日志");
        }

        if (users2List.size()!=0){
            StringBuffer stringBuffer1=new StringBuffer();
            int i=0;
            for (String s1:users2List){
                Users users1 = usersMapper.getUsersByuserId(s1);
                if(users1 != null){
                    if ((users2List.size()-1)==i){
                        stringBuffer1.append(users1.getUserName());
                    } else{
                        stringBuffer1.append(users1.getUserName()+",");
                    }
                }
                i++;
            }
            String s1 = stringBuffer1.toString();
            toJson.setObject(s1+""+users2List.size()+"人"+"无动态");
        }

        // 查询是否允许评论
        SysPara is_comments = sysParaMapper.querySysPara("IS_COMMENTS");
        for (DiaryModel dm : diaryList) {
            //附件处理
            List<Attachment> attachmentList=new ArrayList<Attachment>();
            if(dm.getAttachmentName()!=null&&!"".equals(dm.getAttachmentName())){
                attachmentList= GetAttachmentListUtil.returnAttachment(dm.getAttachmentName(),dm.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"),GetAttachmentListUtil.MODULE_DIARY);
            }
            dm.setAttachment(attachmentList);
            // 查询评论数
            dm.setComTotal(diaryCommentModelMapper.getDiaryCommentCount(dm.getDiaId()));
            // 查询用户信息
            Users usersByuserId = usersMapper.findUsersByuserId(dm.getUserId());
            if(usersByuserId!=null){
                dm.setUserPrivName(usersByuserId.getUserPrivName());
                dm.setDeptName(usersByuserId.getDeptName());
            }
            if (!dm.getUserId().equals(userid)) {
                dm.setIsComments(Integer.valueOf(is_comments.getParaValue()));
            }
            DiaryTop diaryTopByDiaId = diaryTopMapper.getDiaryTopByDiaId(String.valueOf(dm.getDiaId()));
            if (diaryTopByDiaId == null) {
                dm.setTopFlag("0");
            } else {
                dm.setTopFlag("1");
            }
        }
        // 排序
        sortDiaryList(diaryList);
        toJson.setObj(diaryList);

        pageParams.setTotal(u);
        toJson.setTotleNum(pageParams.getTotal());
        toJson.setFlag(0);
        return toJson;
    }

    @Override
    public void exportSelect(Map<String, String> mapSelectParameter, HttpServletRequest request, HttpServletResponse response) {
        ToJson<DiaryModel> toJson = new ToJson<DiaryModel>();
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        Users  users=SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        //查询时间 开始
        /* Date timeBegin = this.getDate(mapSelectParameter.get("startBegin"), "yyyy-mm-dd");*/
        String startBegin = mapSelectParameter.get("data.startBegin");
        String time = getString(mapSelectParameter.get("data.time"));
        //查询时间 结束
        /*Date timeEnd = this.getDate(mapSelectParameter.get("startEnd"), "yyyy-mm-dd");*/
        String startEnd = mapSelectParameter.get("data.startEnd");
        //查询范围 用户范围
        String userIdStrings = getString(mapSelectParameter.get("data.userId"));
        //查询范围 角色范围
        String userPrivStrings = getString(mapSelectParameter.get("data.userPriv"));
        //查询范围 用户范围
        String deptIdStrings = getString(mapSelectParameter.get("data.deptIds"));
        //传值map
        Map<String, Object> diaryMap = new HashMap<String, Object>();
        HttpSession session = request.getSession();
        String userid = (String) session.getAttribute("userId");
        diaryMap.put("userId", userid);
        diaryMap.put("diaType", "1");
        diaryMap.put("time", time);
        diaryMap.put("adminType",users.getUserPriv());

        // 拼写时间
        if (startBegin != null&&!"".equals(startBegin)) {
            diaryMap.put("timeBegin", startBegin+" 00:00:00");
        }
        if (startEnd != null&&!"".equals(startEnd)) {
            diaryMap.put("timeEnd", startEnd+" 23:59:59");
        }
        //时间日期
        List<String> userIdList = new ArrayList<String>();

        List<DiaryModel> diaryAllList =new ArrayList<DiaryModel>();
        //判断是否是管理员
        Department deptById = departmentMapper.getDeptById(users.getDeptId());
        List<Department> list1 = departmentMapper.getChDeptByDeptNo(deptById.getDeptId(),deptById.getDeptNo());

        int size  = list1.size();
        String [] arr ;
        if (!"".equals(deptIdStrings)&&!"undefined".equals(deptIdStrings)) {
            arr= deptIdStrings.split(",");
        }else {
            arr= new String[size+1];
            int x=0;
            for (Department department:list1){
                arr[x]=department.getDeptId()+"";
                x++;
            }
            arr[size]=users.getDeptId()+"";
        }
        List<Users> userPrivsByDeptID = usersMapper.getUserPrivsByDeptID(arr);
        StringBuffer stringBuffer=new StringBuffer();
        List<String> list=new ArrayList<>();
        if (!"".equals(userPrivStrings)&&!"undefined".equals(userPrivStrings)) {
            String[] userPrivs = userPrivStrings.split(",");
            int n=0;
            for(String s:userPrivs){
                UserPriv userPriv = userPrivMapper.selectByPrimaryKey(Integer.parseInt(s));
                for (Users users1: userPrivsByDeptID){
                    if (users1.getUserPrivNo()>=userPriv.getPrivNo()){
                        if (n==0){
                            stringBuffer.append(users1.getUserId());
                        }else if (n > 0){
                            stringBuffer.append(","+users1.getUserId());
                        }
                        n++;
                    }


                }
            }
        }else {
            int n=0;
            for (Users users1: userPrivsByDeptID){

                if (users1.getUserPriv()>=users.getUserPriv()){
                    if (n==0){
                        stringBuffer.append(users1.getUserId());
                    }else if (n > 0){
                        stringBuffer.append(","+users1.getUserId());
                    }
                    n++;
                }
            }
        }
        String s=new String(stringBuffer);
        String [] split=s.split(",");


        if (!"".equals(userIdStrings)&&!"undefined".equals(userIdStrings)) {
            String[] userIds = userIdStrings.split(",");
            for (String s1:userIds){
                for (String s2:split){
                    if (s1==s2){
                        list.add(s1);
                    }
                }
            }
            List<String> list2=Arrays.asList(userIds);
            userIdList.addAll(list2);
        }else {
            for (String s2:split){
                list.add(s2);
            }
            userIdList=list;
        }
        diaryMap.put("userIds", userIdList);
        //查询范围  1、所有人   2、我自己的  3、 共享给我的  4、 有权限查看的 5.根据日期查询
        String queryScope = getString(mapSelectParameter.get("data.queryScope"));
        List<DiaryModel> diaryList = new ArrayList<DiaryModel>();
        switch (Integer.parseInt(queryScope)) {
            case 1:
                diaryList = diaryModelMapper.diarySelectOne(diaryMap);
                break;
            case 2:
                diaryList = diaryModelMapper.diarySelectTwo(diaryMap);
                break;
            case 3:
                diaryList = diaryModelMapper.diarySelectThree(diaryMap);
                break;
            case 4:
                diaryList = diaryModelMapper.diarySelectOne(diaryMap);
                break;
            case 5:
                diaryList = diaryModelMapper.diarySelectFive(diaryMap);
                break;
            default:
                toJson.setMsg("没有该查询条件设置");
                break;
        }
        // 查询是否允许评论
        /*SysPara is_comments = sysParaMapper.querySysPara("IS_COMMENTS");*/
        for (DiaryModel dm : diaryList) {
            //附件处理
            List<Attachment> attachmentList=new ArrayList<Attachment>();
            if(dm.getAttachmentName()!=null&&!"".equals(dm.getAttachmentName())){
                attachmentList= GetAttachmentListUtil.returnAttachment(dm.getAttachmentName(),dm.getAttachmentId(),"xoa" + (String) request.getSession().getAttribute("loginDateSouse"),GetAttachmentListUtil.MODULE_DIARY);
            }
            dm.setAttachment(attachmentList);

            // 查询用户信息
            Users usersByuserId = usersMapper.findUsersByuserId(dm.getUserId());
            if(usersByuserId!=null){
                dm.setUserPrivName(usersByuserId.getUserPrivName());
                dm.setDeptName(usersByuserId.getDeptName());
            }
        }
        try {
            HSSFWorkbook workbooks = new HSSFWorkbook();
            HSSFCellStyle style = workbooks.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            // 创建一个字体样式
            HSSFFont font = workbooks.createFont();
            font.setFontHeightInPoints((short)16);
            font.setBold(true);
            style.setFont(font);
            HSSFSheet sheet = workbooks.createSheet("学习经历信息导出");
            sheet.setDefaultColumnWidth(25);
            sheet.setDefaultRowHeightInPoints(25);
            CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, 13);
            sheet.addMergedRegion(cellRangeAddress);
            HSSFRow rowTitle = sheet.createRow(0);
            HSSFCell cellTitle = rowTitle.createCell(0);
            // 为标题设置背景颜色
            style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.index);
            cellTitle.setCellValue("日志信息导出");
            cellTitle.setCellStyle(style);
            String[] secondTitles = {"用户名","用户角色", "所属部门", "日志日期", "日志类型", "日志标题", "日志内容", "日志附件"
            };
            HSSFWorkbook workbook2 = ExcelUtil.makeSecondHead(workbooks, secondTitles);
            String[] beanProperty = {"userName", "userPrivName", "deptName","diaTime", "diaType", "subject", "content", "attachmentName"};
            for (DiaryModel dm : diaryList) {
                if(!StringUtils.checkNull(dm.getDiaType())){
                    if (dm.getDiaType().equals("1")){
                        dm.setDiaType("工作日志");
                    }
                    if (dm.getDiaType().equals("2")){
                        dm.setDiaType("个人日志");
                    }
                }
                if(!StringUtils.checkNull(dm.getContent())){
                    dm.setContent( dm.getContent().replaceAll("\\&[a-zA-Z]{0,9};", "").replaceAll("<[^>]*>", "\n\t"));
                }
            }
            HSSFWorkbook workbook = ExcelUtil.exportExcelData(workbook2, diaryList, beanProperty);
            ServletOutputStream out = response.getOutputStream();
            String filename = "日志信息导出.xls"; //考虑多语言
            filename = FileUtils.encodeDownloadFilename(filename,
                    request.getHeader("user-agent"));
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-disposition",
                    "attachment;filename=" + filename);
            workbook.write(out);
            out.close();
        }  catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-6-14 下午2:12:14
     * 方法介绍:   递归获取部门
     * 参数说明:   @param parseInt
     * 参数说明:   @return
     *
     * @return List<Department>
     */
    private List<Department> getchDept(int parseInt,List<Department> childDept) {
        List<Department> depts = new ArrayList<Department>();
        depts = departmentService.getChDept(parseInt);
        for (Department d : depts) {
            childDept.addAll(getchDept(d.getDeptId(),new ArrayList<Department>()));
        }
        depts.addAll(childDept);
        return depts;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-6-14 下午2:13:54
     * 方法介绍:   格式化时间
     * 参数说明:   @param str
     * 参数说明:   @param format
     * 参数说明:   @return
     *
     * @return DateTest
     */
    public static Date getDate(Object str, String format) {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String s = getString(str);
        if (!"".equals(s)) {
            try {
                return sdf.parse(s);
            } catch (Exception e) {
                return null;
            }
        }
        return null;
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-6-13 下午3:12:59
     * 方法介绍:   字符串转换
     * 参数说明:   @param str
     * 参数说明:   @return
     *
     * @return String
     */
    public static String getString(Object str) {
        if (str == null) {
            return "";
        }
        return String.valueOf(str);
    }

    /**
     * 创建作者:   杨 胜
     * 创建日期:   2017-5-3 下午2:54:56
     * 方法介绍:   判断已读未读
     * 参数说明:   @param userId
     * 参数说明:   @param readers
     * 参数说明:   @return
     *
     * @return String 返回字符串“1”为已读 “0”为未读通过前端判断进行辨别
     */
    public String readerFlag(String userId, String readers) {
        if (readers != null && !"".equals(readers)) {
            String[] readersStrings = readers.split(",");
            List<String> userList = Arrays.asList(readersStrings);
            if (userList.contains(userId)) {
                return "1";
            } else {
                return "0";
            }
        }
        return "0";
    }

    public static String decompress(String data) throws UnsupportedEncodingException {
        return decompress(data, "ISO-8859-1");

//		   for(DiaryModel dm:diaryAllList){
//			 System.out.println("---------------getCompressContentBefore-------------"+dm.getCompressContent());
//			 String compressString=null;
//			try {
//				compressString=decompress(URLDecoder.decode(dm.getCompressContent(), "ISO-8859-1"));
//			} catch (UnsupportedEncodingException e) {
//				e.printStackTrace();
//			}
//		      dm.setCompressContent(compressString);
//		      System.out.println("---------------getCompressContentAfter-------------"+dm.getCompressContent());
//		   }
    }

    public static String decompress(String data, String charset) throws UnsupportedEncodingException {

        byte[] bytes = data.getBytes(charset);

        byte[] output = new byte[1024];

        Inflater decompresser = new Inflater();
        decompresser.reset();
        decompresser.setInput(bytes);

        ByteArrayOutputStream o = new ByteArrayOutputStream(bytes.length);
        try {
            byte[] buf = new byte[1024];
            while (!decompresser.finished()) {
                int i = decompresser.inflate(buf);
                o.write(buf, 0, i);
            }
            output = o.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                o.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        decompresser.end();
        return new String(output);
    }


//	public String transfor(String s){
//		byte[] compressByte=s.getBytes();
//    	InputStream tempIs=new ByteArrayInputStream(compressByte);
//    	InputStreamReader isr=null;
//    	try {
//		   isr=new InputStreamReader(tempIs,"Unicode");
//		} catch (UnsupportedEncodingException e) {
//            loger.info("mediumblob二进制转化异常");
//			e.printStackTrace();
//		}
//    	BufferedReader br=new BufferedReader(isr);
//    	StringBuffer compressBuffer=null;
//    	try {
//    		compressBuffer=new StringBuffer();
//			while (br.readLine()!=null) {
//    			compressBuffer.append(br.readLine());
//			}
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//    	String  compressString=null;
//    	try {
//			compressString=new String(compressBuffer.toString().getBytes("ISO-8859-1"),"UTF-8");
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		}
//		return compressString;
//	}

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年7月5日 下午15:12:05
     * 方法介绍:   添加工作日志评论
     *
     * @return ToJson
     */
    @Transactional
    @Override
    public ToJson<DiaryCommentModel> insertDiaryComment(DiaryCommentModel diaryCommentModel, HttpServletRequest request) {
        ToJson<DiaryCommentModel> json = new ToJson<DiaryCommentModel>(1, "error");
        int count = 0;
        try {
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
            diaryCommentModel.setUserId(user.getUserId());
            Calendar c = Calendar.getInstance();
            diaryCommentModel.setSendTime(DateFormat.getFormatByUse(" yyyy-MM-dd HH:mm:ss", c.getTime()));
            diaryCommentModel.setCommentFlag("0");
            if (StringUtils.checkNull(diaryCommentModel.getAttachmentId())) {
                diaryCommentModel.setAttachmentId("");
            }
            if (StringUtils.checkNull(diaryCommentModel.getAttachmentName())) {
                diaryCommentModel.setAttachmentName("");
            }
            count = diaryCommentModelMapper.insertDiaryComment(diaryCommentModel);
            if (count != 0) {
                addAffairsCom(diaryCommentModel,request);
                json.setMsg("ok");
                json.setFlag(0);
            }
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            L.e("DiaryServiceImpl insertDiaryComment:" + e);
        }
        return json;
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年7月5日 下午16:01:29
     * 方法介绍:   获取所有工作日志评论
     *
     * @return ToJson
     */
    @Override
    public ToJson<DiaryCommentModel> getDiaryCommentByDiaId(String diaId) {
        ToJson<DiaryCommentModel> json = new ToJson<DiaryCommentModel>(1, "error");
        try {
            List<DiaryCommentModel> diaryCommentModelList = new ArrayList<DiaryCommentModel>();
            List<DiaryCommentReplyModel> diaryCommentReplyModelList = new ArrayList<DiaryCommentReplyModel>();
            if (!StringUtils.checkNull(diaId)) {
                diaryCommentModelList = diaryCommentModelMapper.getDiaryCommentByDiaId(diaId);
            }
            for (DiaryCommentModel diaryCommentModel : diaryCommentModelList) {
                if(!StringUtils.checkNull(diaryCommentModel.getSendTime())){
                    diaryCommentModel.setSendTime(diaryCommentModel.getSendTime().substring(0,diaryCommentModel.getSendTime().length()-2));
                }
                Users user = usersService.findUsersByuserId(diaryCommentModel.getUserId());
                if (user != null) {
                    diaryCommentModel.setUserName(user.getUserName());
                    diaryCommentReplyModelList = diaryCommentReplyModelMapper.getCommentReplyByCommentId(diaryCommentModel.getCommentId().toString());
                    diaryCommentModel.setDiaryCommentReplyModelList(diaryCommentReplyModelList);
                    for(DiaryCommentReplyModel diaryCommentReplyModel:diaryCommentReplyModelList){
                        if(diaryCommentReplyModel.getReplyer()!=null){
                            if(usersService.findUsersByuserId(diaryCommentReplyModel.getReplyer())!=null){
                                diaryCommentReplyModel.setReplyerName(usersService.findUsersByuserId(diaryCommentReplyModel.getReplyer()).getUserName());
                            }
                        }
                        if(diaryCommentReplyModel.getToId()!=null){
                            if(usersService.findUsersByuserId(diaryCommentReplyModel.getToId())!=null){
                                diaryCommentReplyModel.setToName(usersService.findUsersByuserId(diaryCommentReplyModel.getToId()).getUserName());
                            }
                        }
                    }
                } else {
                    diaryCommentModel.setUserName("用户不存在");
                }

            }
            json.setObj(diaryCommentModelList);
            json.setMsg("ok");
            json.setFlag(0);

        } catch (Exception e) {
            json.setMsg(e.getMessage());
            L.e("DiaryServiceImpl getDiaryCommentByDiaId:" + e);
        }
        return json;
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年7月5日 下午16:54:55
     * 方法介绍:   添加工作日志评论回复
     *
     * @return int 添加条数
     */
    @Transactional
    @Override
    public ToJson<DiaryCommentReplyModel> insertCommentReply(DiaryCommentReplyModel diaryCommentReplyModel, HttpServletRequest request) {
        ToJson<DiaryCommentReplyModel> json = new ToJson<DiaryCommentReplyModel>(1, "error");
        int count = 0;
        try {
            Calendar c = Calendar.getInstance();
            diaryCommentReplyModel.setReplyTime(DateFormat.getFormatByUse(" yyyy-MM-dd HH:mm:ss", c.getTime()));
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
            diaryCommentReplyModel.setReplyer(user.getUserId());
            DiaryCommentModel diaryCommentModel  = diaryCommentModelMapper.getDiaryCommentById(diaryCommentReplyModel.getCommentId());
            diaryCommentReplyModel.setDiaId(diaryCommentModel.getDiaId());
            count = diaryCommentReplyModelMapper.insertCommentReply(diaryCommentReplyModel);
            if (count != 0) {
                addAffairsComReply(diaryCommentReplyModel,request);
                json.setMsg("ok");
                json.setFlag(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
            L.e("DiaryServiceImpl insertCommentReply:" + e);
        }
        return json;
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年7月5日 下午19:21:00
     * 方法介绍:   根据评论id删除评论
     *
     * @return
     */
    @Transactional
    @Override
    public ToJson<DiaryCommentModel> delDiaryCommentByCommentId(String commentId) {
        ToJson<DiaryCommentModel> json = new ToJson<DiaryCommentModel>(1, "error");
        int count1 = 0;
        int count2 = 0;
        try {
            count1 = diaryCommentModelMapper.delDiaryCommentByCommentId(commentId);
            count2 = diaryCommentReplyModelMapper.delCommentReplyByCommentId(commentId);
            if (count1 != 0) {
                json.setMsg("ok");
                json.setFlag(0);
            }
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            L.e("DiaryServiceImpl delDiaryCommentByCommentId:" + e);
        }
        return json;
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年7月5日 下午19:21:00
     * 方法介绍:   根据评论id删除评论回复
     *
     * @return
     */
    @Transactional
    @Override
    public ToJson<DiaryCommentReplyModel> delCommentReplyByReplyId(String replyId) {
        ToJson<DiaryCommentReplyModel> json = new ToJson<DiaryCommentReplyModel>(1, "error");
        int count = 0;
        try {
            count = diaryCommentReplyModelMapper.delCommentReplyByReplyId(replyId);
            if (count != 0) {
                json.setMsg("ok");
                json.setFlag(0);
            }
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            L.e("DiaryServiceImpl delCommentReplyByReplyId:" + e);
        }
        return json;
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年7月6日 下午10:04:00
     * 方法介绍:   根据日志id查询 评论的数量
     *
     * @return int
     */
    @Override
    public ToJson<DiaryCommentModel> getDiaryCommentCount(Integer diaId) {
        ToJson<DiaryCommentModel> json = new ToJson<DiaryCommentModel>(1, "error");
        try {
            int count = diaryCommentModelMapper.getDiaryCommentCount(diaId);
            json.setTotleNum(count);
            json.setMsg("ok");
            json.setFlag(0);
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            L.e("DiaryServiceImpl getDiaryCommentCount:" + e);
        }
        return json;
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年7月6日 下午13:40:10
     * 方法介绍:   工作日志置顶
     *
     * @return ToJson
     */
    @Transactional
    @Override
    public ToJson<DiaryModel> insertDiaryTop(String diaId, HttpServletRequest request) {
        ToJson<DiaryModel> json = new ToJson<DiaryModel>(1, "error");
        try {
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
            DiaryTop diaryTop = diaryTopMapper.getDiaryTopByDiaId(diaId);
            int count = 0;
            if (diaryTop != null) {
                String userId = diaryTop.getUserId();
                diaryTop.setUserId(userId + "," + user.getUserId());
                count = diaryTopMapper.updUserIdByDiaId(diaryTop);
            } else {
                diaryTop = new DiaryTop();
                diaryTop.setUserId(user.getUserId());
                diaryTop.setDiaCate(1);
                diaryTop.setDiaId(Integer.valueOf(diaId));
                count = diaryTopMapper.insertDiaryTop(diaryTop);
            }
            if (count != 0) {
                List<DiaryModel> diaryModelList = diaryTopMapper.getOrderDiary(user.getUserId());
                for (DiaryModel diaryModel : diaryModelList) {
                    if (diaryModel.getDiaryTop() == null) {
                        diaryModel.setTopFlag("0");
                    } else {
                        diaryModel.setTopFlag("1");
                    }
                }
                json.setObj(diaryModelList);
                json.setMsg("ok");
                json.setFlag(0);
            }
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            L.e("DiaryServiceImpl getDiaryByDiaryTop:" + e);
        }
        return json;
    }

    /**
     * 创建作者:   牛江丽
     * 创建日期:   2017年7月6日 下午16:10:10
     * 方法介绍:   取消工作日志置顶
     *
     * @return ToJson
     */
    @Transactional
    @Override
    public ToJson<DiaryModel> deleteDiaryTop(String diaId, HttpServletRequest request) {
        ToJson<DiaryModel> json = new ToJson<DiaryModel>(1, "error");
        try {
            int count = 0;
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users user = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
            DiaryTop diaryTop = diaryTopMapper.getDiaryTopByDiaId(diaId);
            StringBuffer newUserId = new StringBuffer();
            if(diaryTop!=null && !StringUtils.checkNull(diaryTop.getUserId())){
                String[] userIdArray = diaryTop.getUserId().split(",");
                if (userIdArray.length == 1) {
                    count = diaryTopMapper.delDiaryTopByDiaId(diaId);
                } else {
                    for (String userId : userIdArray) {
                        if (!userId.equals(user.getUserId())) {
                            newUserId.append(userId + ",");
                        }
                    }
                    diaryTop.setUserId(newUserId.toString());
                    diaryTop.setDiaId(Integer.valueOf(diaId));
                    count = diaryTopMapper.updUserIdByDiaId(diaryTop);
                }
            }
            if (count != 0) {
                List<DiaryModel> diaryModelList = diaryTopMapper.getOrderDiary(user.getUserId());
                for (DiaryModel diaryModel : diaryModelList) {
                    if (diaryModel.getDiaryTop() == null) {
                        diaryModel.setTopFlag("0");
                    } else {
                        diaryModel.setTopFlag("1");
                    }
                }
                json.setObj(diaryModelList);
                json.setMsg("ok");
                json.setFlag(0);
            }
        } catch (Exception e) {
            json.setMsg(e.getMessage());
            L.e("DiaryServiceImpl deleteDiaryTop:" + e);
        }
        return json;
    }

    /**
     * @作者：张航宁
     * @时间：2017/7/20
     * @介绍：获取浏览人员信息
     * @参数：diaId
     */
    @Override
    public ToJson<DiaryModel> getReadUsers(Integer diaId) {
        ToJson<DiaryModel> json = new ToJson<DiaryModel>();
        try {
            DiaryModel dm = diaryModelMapper.getReadUsers(diaId);
            String readers = dm.getReaders();
            StringBuffer readersName = new StringBuffer();
            if (!StringUtils.checkNull(readers)) {
                List<Users> usersByUserIds = usersMapper.getUsersByUserIds(readers.split(","));
                int count = 0;
                for (Users u : usersByUserIds) {
                    if (count < 9) {
                        readersName.append(u.getUserName() + ",");
                    } else {
                        readersName.append(u.getUserName() + "等" + usersByUserIds.size() + "人浏览过该日志");
                        break;
                    }
                    count++;
                }
                if (count < 9) {
                    // 去掉最后一个逗号
                    dm.setReadersName(readersName.toString().substring(0, readersName.toString().length() - 1));
                }
            } else {
                dm.setReadersName("暂无浏览");
            }

            json.setObject(dm);
            json.setMsg("ok");
            json.setFlag(0);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }

    @Override
    public ToJson<DiaryModel> selectShareName(HttpServletRequest request) {
        ToJson<DiaryModel> json = new ToJson<DiaryModel>();
        try {
            Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
            Users  users=SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
            //每次发送日志之前，若选中按钮，这显示默认共享名称
            DiaryModel diaryModel= new DiaryModel();
            List<DiaryModel> dm = diaryModelMapper.selectShareName(users.getUserId());
            if(dm.size()>0&&dm!=null){
                for(int i=0;i<dm.size();i++){
                    //只获取最新的一条
                    diaryModel = (DiaryModel)dm.get(0);
                }
            }

            //把id变成名字
            //定义用于拼接角色名称的字符串
            StringBuffer sb = new StringBuffer();
            if(diaryModel!=null) {
                String userName = diaryModel.getToId();
                String[] temp = userName.split(",");
                for (int i = 0; i < temp.length; i++) {
                    if (!StringUtils.checkNull(temp[i])) {
                        String name = usersMapper.getUsernameByUserId(temp[i]);
                        if (!StringUtils.checkNull(name)) {
                            if (i < temp.length - 1) {
                                sb.append(name).append(",");
                            } else {
                                sb.append(name);
                            }
                        }
                    }
                }
            }
            diaryModel.setSm(sb.toString());
            json.setObject(diaryModel);
            json.setMsg("ok");
            json.setFlag(0);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg("err");
            json.setFlag(1);
        }
        return json;
    }



    // 置顶排序
    private void sortDiaryList(List<DiaryModel> diaryList) {
        Collections.sort(diaryList, new Comparator<DiaryModel>() {
            @Override
            public int compare(DiaryModel o1, DiaryModel o2) {
                //都被置顶
                if (o1.getTopFlag().equals("1") && o2.getTopFlag().equals("1")) {
                    if(o1.getDiaryTop()==null){
                        return  1;
                    }else if(o2.getDiaryTop()==null){
                        return -1;
                    }else if(o1.getDiaryTop()!=null&&o2.getDiaryTop()!=null){
                        if (o1.getDiaryTop().getTopId()<o2.getDiaryTop().getTopId()) {
                            return  1;
                        }else{
                            return -1;
                        }
                    }
                }
                // 其中一个被置顶
                if(o1.getTopFlag().equals("1")&& o2.getTopFlag().equals("0")){
                    return -1;
                }
                if(o1.getTopFlag().equals("0")&& o2.getTopFlag().equals("1")){
                    return  1;
                }
                return 0;
            }
        });
    }

    /**
     * 共享日志添加提醒
     * @param diaryModel
     */
    @Async
    public void addAffairs(final DiaryModel diaryModel, HttpServletRequest request) {
        final String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        final Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        this.threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                ContextHolder.setConsumerType("xoa" + sqlType);
                SmsBody smsBody = new SmsBody();
                smsBody.setFromId(diaryModel.getUserId());
                smsBody.setContent("请查看我的共享日志！主题：" + diaryModel.getSubject());
                smsBody.setSendTime(DateFormat.getTime(DateFormat.getStrDate(new Date())));
                SysCode sysCode = new SysCode();
                sysCode.setCodeName("工作日志");
                sysCode.setParentNo("SMS_REMIND");
                if (sysCodeMapper.getCodeNoByNameAndParentNo(sysCode) != null) {
                    smsBody.setSmsType(sysCodeMapper.getCodeNoByNameAndParentNo(sysCode).getCodeNo());
                }
                if (!StringUtils.checkNull(diaryModel.getAttachmentId()) && !StringUtils.checkNull(diaryModel.getAttachmentName())) {
                    smsBody.setIsAttach("1");
                }
                String toUserId=diaryModel.getToId();
                smsBody.setRemindUrl("/diary/details?ID="+diaryModel.getDiaId());//flag未用，方便拼接
                smsBody.setEditFlag(diaryModel.getEditFlag());
                String title = users.getUserName() + "：请查看我的日志！";
                String context = "主题:" + diaryModel.getSubject();
                smsService.saveSms(smsBody, toUserId, "1", "1", title, context, sqlType);
                qywxService.sendMsg(Arrays.asList(toUserId.split(",")),title,context,smsBody.getRemindUrl(),false);
            }
        });

    }

    /**
     * 共享评论日志添加提醒
     * 张丽军
     * @param diaryCommentModel
     */
    @Async
    public void addAffairsCom(final DiaryCommentModel diaryCommentModel, HttpServletRequest request) {
        final String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        final Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        this.threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                ContextHolder.setConsumerType("xoa" + sqlType);
                SmsBody smsBody = new SmsBody();
                smsBody.setFromId(diaryCommentModel.getUserId());
                smsBody.setContent("请查看我的共享评论日志！主题：" + diaryCommentModel.getContent());
                smsBody.setSendTime(DateFormat.getTime(DateFormat.getStrDate(new Date())));
                SysCode sysCode = new SysCode();
                sysCode.setCodeName("工作日志");
                sysCode.setParentNo("SMS_REMIND");
                if (sysCodeMapper.getCodeNoByNameAndParentNo(sysCode) != null) {
                    smsBody.setSmsType(sysCodeMapper.getCodeNoByNameAndParentNo(sysCode).getCodeNo());
                }
                if (!StringUtils.checkNull(diaryCommentModel.getAttachmentId()) && !StringUtils.checkNull(diaryCommentModel.getAttachmentName())) {
                    smsBody.setIsAttach("1");
                }
                String toUserId=diaryCommentModel.getUserId();
                smsBody.setRemindUrl("/diary/details?ID="+diaryCommentModel.getDiaId());//flag未用，方便拼接
                smsBody.setEditFlag(diaryCommentModel.getEditFlag());
                String title = users.getUserName() + "：请查看我的日志！";
                String context = "主题:" + diaryCommentModel.getContent();
                smsService.saveSms(smsBody, toUserId, "1", "1", title, context, sqlType);
            }
        });

    }
    /**
     * 共享评论、回复日志添加提醒
     * 张丽军
     * @param diaryCommentReplyModel
     */
    @Async
    public void addAffairsComReply(final DiaryCommentReplyModel diaryCommentReplyModel, HttpServletRequest request) {
        final String sqlType = (String) request.getSession().getAttribute("loginDateSouse");
        Cookie redisSessionId = CookiesUtil.getCookieByName(request, "redisSessionId");
        final Users users = SessionUtils.getSessionInfo(request.getSession(), Users.class, new Users(),redisSessionId);
        this.threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                ContextHolder.setConsumerType("xoa" + sqlType);
                SmsBody smsBody = new SmsBody();
                smsBody.setFromId(diaryCommentReplyModel.getReplyer());
                smsBody.setContent("请查看我的共享评论、回复日志！主题：" + diaryCommentReplyModel.getReplyComment());
                smsBody.setSendTime(DateFormat.getTime(DateFormat.getStrDate(new Date())));
                SysCode sysCode = new SysCode();
                sysCode.setCodeName("工作日志");
                sysCode.setParentNo("SMS_REMIND");
                if (sysCodeMapper.getCodeNoByNameAndParentNo(sysCode) != null) {
                    smsBody.setSmsType(sysCodeMapper.getCodeNoByNameAndParentNo(sysCode).getCodeNo());
                }
             /*   if (!StringUtils.checkNull(diaryCommentModel.getAttachmentId()) && !StringUtils.checkNull(diaryCommentModel.getAttachmentName())) {
                    smsBody.setIsAttach("1");
                }*/
                String toUserId=diaryCommentReplyModel.getToId();
                smsBody.setRemindUrl("/diary/details?ID="+diaryCommentReplyModel.getDiaId());//flag未用，方便拼接
                smsBody.setEditFlag(diaryCommentReplyModel.getEditFlag());
                String title = users.getUserName() + "：请查看我的日志！";
                String context = "主题:" + diaryCommentReplyModel.getReplyComment();
                smsService.saveSms(smsBody, toUserId, "1", "1", title, context, sqlType);
                qywxService.sendMsg(Arrays.asList(toUserId.split(",")),context,title,"/ewx/consult?id="+diaryCommentReplyModel.getDiaId(),false);
            }
        });

    }


}
